'''
Created on Mar 17, 2013

@author: kafkef
'''


import os
import json

from PyQt4.QtGui import *
from PyQt4.QtWebKit import *
from PyQt4.QtCore import QUrl, pyqtSlot, Qt, SIGNAL

import dexen
from dexen.system.client.ui.dialogs.archive_dlg import ArchiveDialog
from dexen.system.client.controller import archive_syncher
from dexen.system.client.db import JobInfo
from dexen.system.client.controller.action_mgr import GetActionMgr,\
    GetAllActionMgrs
from dexen.system.common.base import Individual
from dexen.system.client.ui import GetJobInfoTabWdg


def to_dict(obj):
    if isinstance(obj, Individual):
        d = obj.__dict__
        exclude = ["__modified__", "__archived__"]
        for name in exclude:
            if d.has_key(name):
                del d[name]
        return d
    if isinstance(obj, JobInfo):
        svr_info = obj.get_svr_info()
        return {
            "job_id" : obj.get_id(),
            "job_name" : obj.get_name(),
            "svr_name" : svr_info.get_name(),
            "svr_start_time" : svr_info.get_start_time()
        }
    return {}


class CustomPage(QWidget):
    def __init__(self, folder_name):
        super(CustomPage, self).__init__()
        self.cur_job = GetJobInfoTabWdg().cur_job
        path = os.path.join(dexen.PLUGINS_DIR, folder_name, "index.html")
        print path
        self.view = QWebView()
        self.view.setUrl(QUrl.fromLocalFile(path))
        
        self.setupView()
        self.setupInspector()
        self.splitter = QSplitter(Qt.Vertical)
        
        # Setup layout
        layout = QVBoxLayout()
        self.splitter.addWidget(self.view)
        self.splitter.addWidget(self.webInspector)
        layout.addWidget(self.splitter)
        self.setLayout(layout)
        
        self.connect(self.frame, SIGNAL("javaScriptWindowObjectCleared()"),
                     self.add_javascript_window_object) 
    
    @property
    def frame(self):
        return self.view.page().mainFrame()
        
    def setupView(self):
        self.frame.addToJavaScriptWindowObject("dexen", self)

    def setupInspector(self):
        page = self.view.page()
        page.settings().setAttribute(QWebSettings.DeveloperExtrasEnabled, True)
        self.webInspector = QWebInspector(self)
        self.webInspector.setPage(page)
        self.webInspector.setVisible(False)
        shortcut = QShortcut(self)
        shortcut.setKey(Qt.Key_F9)
        shortcut.activated.connect(self.toggleInspector)
    
    def toggleInspector(self):
        self.webInspector.setVisible(not self.webInspector.isVisible())

    def on_cur_job_changed(self, job_info):
        print "CustomPage::on_cur_job_changed"
        self.cur_job = job_info
        if job_info is None:
            self.frame.evaluateJavaScript("cur_job_changed(null);")
            return
        
        job_info_json = json.dumps(to_dict(job_info))
        self.frame.evaluateJavaScript("cur_job_changed(%s);"%(job_info_json, ))

    def on_inds_updated(self, job_info, inds, islocal):
        print "on inds updated", len(inds)
        job_info_json = json.dumps(to_dict(job_info))
        inds_json = json.dumps([to_dict(ind) for ind in inds])
        self.frame.evaluateJavaScript("on_inds_updated(%s, %s);"%(job_info_json, inds_json))

    @pyqtSlot(result=str)
    def get_all_inds(self):
        act_mgrs = GetAllActionMgrs()
        result = []
        for job_info, act_mgr in act_mgrs.iteritems():
            result.append({"job_info" : to_dict(job_info),
                           "inds" : [to_dict(ind) for ind in act_mgr.get_inds()]})
        #print json.dumps(result)
        return json.dumps(result)

    @pyqtSlot(result=str)
    def get_cur_job(self):
        if not self.cur_job:
            return "null"
        result = json.dumps(to_dict(self.cur_job))
        #print "CustomPage::get_cur_job", result
        return result

    @pyqtSlot(int)
    def download_archive(self, ind_id):
        dlg = ArchiveDialog([ind_id], self.cur_job)
        dlg.exec_()
    
    @pyqtSlot(int, str, result=str)
    def get_archive(self, ind_id, name):
        arc_syncher = archive_syncher.GetArchiveSyncher(self.cur_job)
        return arc_syncher.get_archive(ind_id, name)

    @pyqtSlot()
    def reload(self):
        print "I am in reload"
        self.view.reload()
        self.setupView()

    @pyqtSlot()
    def add_javascript_window_object(self):
        print "Add Javascript Window Object"
        self.setupView()

